/*
 * WordyUI.java
 *
 * Created on 17. juli 2007, 15:55
 */

package glotton;

import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

/**
 *
 * @author  tomase
 */
public class GlottonUI extends javax.swing.JFrame implements SearchListener{
    /**
	 * 
	 */
	private static final long serialVersionUID = -5348696266350098781L;
	private Glotton controller;
    private Finder model;
    
    /** Creates new form WordyUI */
    public GlottonUI() {
        initLookAndFeel();
        setLocationRelativeTo(null);
        initComponents();

        model = new Finder(this);
        controller = new GlottonController(model);
    }
    
    private void setStatusListingWordsInDictionary(){
    	lblStatus.setText("Words in dictionary: " + controller.getDictionarySize());
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {

        dictFileChooser = new javax.swing.JFileChooser();
        groupSorting = new javax.swing.ButtonGroup();
        dialogAbout = new javax.swing.JDialog();
        btnClose = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtpAboutText = new javax.swing.JTextPane();
        jpInput = new javax.swing.JPanel();
        txtUseChars = new javax.swing.JTextField();
        btnFindWords = new javax.swing.JButton();
        lblUseChars = new javax.swing.JLabel();
        jpOutput = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtaWordListing = new javax.swing.JTextArea();
        jpSort = new javax.swing.JPanel();
        jrbAlphabetical = new javax.swing.JRadioButton();
        jrbLongest = new javax.swing.JRadioButton();
        jProgressBar1 = new javax.swing.JProgressBar();
        jToolBar1 = new javax.swing.JToolBar();
        lblStatus = new javax.swing.JLabel();
        jMenuBar2 = new javax.swing.JMenuBar();
        menuFile1 = new javax.swing.JMenu();
        miOpenWordfiles1 = new javax.swing.JMenuItem();
        miClearDicts1 = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JSeparator();
        miExit1 = new javax.swing.JMenuItem();
        menuEdit1 = new javax.swing.JMenu();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem5 = new javax.swing.JMenuItem();
        jMenuBar1 = new javax.swing.JMenuBar();
        menuFile = new javax.swing.JMenu();
        miOpenWordfiles = new javax.swing.JMenuItem();
        miClearDicts = new javax.swing.JMenuItem();
        mirbStayOnTop = new javax.swing.JRadioButtonMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        miExit = new javax.swing.JMenuItem();

        dictFileChooser.setDialogTitle("Choose wordfiles");
        dictFileChooser.setForeground(java.awt.Color.white);
        dictFileChooser.setMultiSelectionEnabled(true);

        dialogAbout.setTitle("About Glotton");

        btnClose.setText("Close");

        jScrollPane2.setViewportView(txtpAboutText);

        javax.swing.GroupLayout dialogAboutLayout = new javax.swing.GroupLayout(dialogAbout.getContentPane());
        dialogAbout.getContentPane().setLayout(dialogAboutLayout);
        dialogAboutLayout.setHorizontalGroup(
            dialogAboutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(dialogAboutLayout.createSequentialGroup()
                .addGroup(dialogAboutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(dialogAboutLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE))
                    .addGroup(dialogAboutLayout.createSequentialGroup()
                        .addGap(170, 170, 170)
                        .addComponent(btnClose)))
                .addContainerGap())
        );
        dialogAboutLayout.setVerticalGroup(
            dialogAboutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(dialogAboutLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 245, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnClose)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Glotton");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setLocationByPlatform(true);

        jpInput.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Letters", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));

        txtUseChars.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtUseCharsKeyPressed(evt);
            }

        });
        


        btnFindWords.setText("Find words");
        btnFindWords.setToolTipText("Get words that use the letters");
        btnFindWords.setActionCommand("findWords");
        btnFindWords.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFindWordsActionPerformed(evt);
            }
        });

        lblUseChars.setText("Letters available:");
        
        txtExisting = new JTextField();
        
        txtExisting.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtUseCharsKeyPressed(evt);
            }

        });
        JLabel lblMatchPattern = new JLabel();
        lblMatchPattern.setText("Match pattern:");

        javax.swing.GroupLayout gl_jpInput = new javax.swing.GroupLayout(jpInput);
        gl_jpInput.setHorizontalGroup(
        	gl_jpInput.createParallelGroup(Alignment.TRAILING)
        		.addGroup(gl_jpInput.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(gl_jpInput.createParallelGroup(Alignment.LEADING)
        				.addComponent(lblUseChars)
        				.addComponent(lblMatchPattern))
        			.addPreferredGap(ComponentPlacement.UNRELATED)
        			.addGroup(gl_jpInput.createParallelGroup(Alignment.TRAILING)
        				.addComponent(txtExisting, GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)
        				.addComponent(txtUseChars, GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE))
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addComponent(btnFindWords)
        			.addContainerGap())
        );
        gl_jpInput.setVerticalGroup(
        	gl_jpInput.createParallelGroup(Alignment.TRAILING)
        		.addGroup(gl_jpInput.createSequentialGroup()
        			.addContainerGap(22, Short.MAX_VALUE)
        			.addGroup(gl_jpInput.createParallelGroup(Alignment.BASELINE)
        				.addComponent(txtUseChars, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(btnFindWords)
        				.addComponent(lblUseChars))
        			.addGap(7)
        			.addGroup(gl_jpInput.createParallelGroup(Alignment.BASELINE)
        				.addComponent(txtExisting, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(lblMatchPattern))
        			.addContainerGap())
        );
        jpInput.setLayout(gl_jpInput);

        jpOutput.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Words", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));

        jtaWordListing.setColumns(20);
        jtaWordListing.setFont(jtaWordListing.getFont().deriveFont((float)13));
        jtaWordListing.setRows(5);
        jScrollPane1.setViewportView(jtaWordListing);

        jpSort.setBorder(javax.swing.BorderFactory.createTitledBorder("Sort by"));

        groupSorting.add(jrbAlphabetical);
        jrbAlphabetical.setText("Alphabetical");
        jrbAlphabetical.setToolTipText("Sorts the words alphabetically");
        jrbAlphabetical.setActionCommand("sortAlpha");
        jrbAlphabetical.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        jrbAlphabetical.setMargin(new java.awt.Insets(0, 0, 0, 0));

        groupSorting.add(jrbLongest);
        jrbLongest.setSelected(true);
        jrbLongest.setText("Longest");
        jrbLongest.setToolTipText("The longest word tops the list");
        jrbLongest.setActionCommand("sortLength");
        jrbLongest.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        jrbLongest.setMargin(new java.awt.Insets(0, 0, 0, 0));

        javax.swing.GroupLayout gl_jpSort = new javax.swing.GroupLayout(jpSort);
        jpSort.setLayout(gl_jpSort);
        gl_jpSort.setHorizontalGroup(
            gl_jpSort.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jrbAlphabetical)
            .addComponent(jrbLongest)
        );
        gl_jpSort.setVerticalGroup(
            gl_jpSort.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(gl_jpSort.createSequentialGroup()
                .addComponent(jrbLongest)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jrbAlphabetical))
        );

        jProgressBar1.setEnabled(false);
        jProgressBar1.setFocusable(false);
        jProgressBar1.setMaximumSize(new java.awt.Dimension(100, 20));
        jProgressBar1.setPreferredSize(new java.awt.Dimension(100, 15));
        jProgressBar1.setRequestFocusEnabled(false);
        
        JPanel jpLanguage = new JPanel();
        
        JRadioButton rdbtnNorwegian = new JRadioButton();
        buttonGroup.add(rdbtnNorwegian);
        rdbtnNorwegian.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent arg0) {
        		controller.setDictionaryTo("no");
        		setStatusListingWordsInDictionary();
        	}
        });
        rdbtnNorwegian.setToolTipText("Use Norwegian wordlists");
        rdbtnNorwegian.setText("Norwegian");
        rdbtnNorwegian.setMargin(new Insets(0, 0, 0, 0));
        rdbtnNorwegian.setActionCommand("sortAlpha");
        
        JRadioButton rdbtnEnglish = new JRadioButton();
        buttonGroup.add(rdbtnEnglish);
        rdbtnEnglish.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
        		controller.setDictionaryTo("en");
        		setStatusListingWordsInDictionary();
        	}
        });
        rdbtnEnglish.setToolTipText("Use English wordlists");
        rdbtnEnglish.setText("English");
        rdbtnEnglish.setSelected(true);
        rdbtnEnglish.setMargin(new Insets(0, 0, 0, 0));
        rdbtnEnglish.setActionCommand("sortLength");
        GroupLayout gl_jpLanguage = new GroupLayout(jpLanguage);
        gl_jpLanguage.setHorizontalGroup(
        	gl_jpLanguage.createParallelGroup(Alignment.LEADING)
        		.addGap(0, 87, Short.MAX_VALUE)
        		.addComponent(rdbtnNorwegian)
        		.addComponent(rdbtnEnglish)
        );
        gl_jpLanguage.setVerticalGroup(
        	gl_jpLanguage.createParallelGroup(Alignment.LEADING)
        		.addGap(0, 63, Short.MAX_VALUE)
        		.addGroup(gl_jpLanguage.createSequentialGroup()
        			.addComponent(rdbtnEnglish)
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addComponent(rdbtnNorwegian))
        );
        jpLanguage.setLayout(gl_jpLanguage);

        javax.swing.GroupLayout gl_jpOutput = new javax.swing.GroupLayout(jpOutput);
        gl_jpOutput.setHorizontalGroup(
        	gl_jpOutput.createParallelGroup(Alignment.TRAILING)
        		.addGroup(gl_jpOutput.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(gl_jpOutput.createParallelGroup(Alignment.TRAILING)
        				.addComponent(jProgressBar1, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE)
        				.addComponent(jScrollPane1, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE))
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addGroup(gl_jpOutput.createParallelGroup(Alignment.LEADING)
        				.addComponent(jpLanguage, GroupLayout.PREFERRED_SIZE, 87, GroupLayout.PREFERRED_SIZE)
        				.addComponent(jpSort, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        			.addContainerGap())
        );
        gl_jpOutput.setVerticalGroup(
        	gl_jpOutput.createParallelGroup(Alignment.LEADING)
        		.addGroup(gl_jpOutput.createSequentialGroup()
        			.addGroup(gl_jpOutput.createParallelGroup(Alignment.LEADING)
        				.addGroup(gl_jpOutput.createSequentialGroup()
        					.addComponent(jpSort, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        					.addGap(16)
        					.addComponent(jpLanguage, GroupLayout.PREFERRED_SIZE, 63, GroupLayout.PREFERRED_SIZE))
        				.addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE))
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addComponent(jProgressBar1, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE))
        );
        jpOutput.setLayout(gl_jpOutput);

        jToolBar1.setRollover(true);

        lblStatus.setText("Status");
        jToolBar1.add(lblStatus);

        menuFile1.setText("File");

        miOpenWordfiles1.setMnemonic('o');
        miOpenWordfiles1.setText("Open wordfiles...");
        miOpenWordfiles1.setToolTipText("Select a set of files with words to search");
        miOpenWordfiles1.setActionCommand("loadDicts");
        miOpenWordfiles1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miOpenWordfilesActionPerformed(evt);
            }
        });
        menuFile1.add(miOpenWordfiles1);


        miClearDicts1.setMnemonic('c');
        miClearDicts1.setText("Clear wordfiles");
        miClearDicts1.setToolTipText("Empty the internal dictionary");
        miClearDicts1.setActionCommand("clearDicts");
        menuFile1.add(miClearDicts1);
        menuFile1.add(jSeparator2);

        miExit1.setMnemonic('x');
        miExit1.setText("Exit");
        miExit1.setToolTipText("Exit application");
        menuFile1.add(miExit1);

        jMenuBar2.add(menuFile1);

        menuEdit1.setText("Edit");

        jMenuItem4.setText("Paste letters from clipboard");
        jMenuItem4.setToolTipText("Pastes clipboard contents into the Letters field");
        jMenuItem4.setActionCommand("pasteLetters");
        menuEdit1.add(jMenuItem4);

        jMenuItem5.setText("Copy top word to clipboard");
        jMenuItem5.setToolTipText("Copies the top word to the clipboard");
        jMenuItem5.setActionCommand("copyTopWord");
        menuEdit1.add(jMenuItem5);

        jMenuBar2.add(menuEdit1);

        menuFile.setText("File");

        miOpenWordfiles.setMnemonic('o');
        miOpenWordfiles.setText("Open wordfiles...");
        miOpenWordfiles.setToolTipText("Select a set of files with words to search");
        miOpenWordfiles.setActionCommand("loadDicts");
        miOpenWordfiles.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miOpenWordfilesActionPerformed(evt);
            }
        });
        menuFile.add(miOpenWordfiles);

        miClearDicts.setMnemonic('c');
        miClearDicts.setText("Clear wordfiles");
        miClearDicts.setToolTipText("Empty the internal dictionary");
        miClearDicts.setActionCommand("clearDicts");
        miClearDicts.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miClearDictsActionPerformed(evt);
            }
        });
        menuFile.add(miClearDicts);

        mirbStayOnTop.setText("Stay on top");
        mirbStayOnTop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mirbStayOnTopActionPerformed(evt);
            }
        });
        menuFile.add(mirbStayOnTop);
        menuFile.add(jSeparator1);

        miExit.setMnemonic('x');
        miExit.setText("Exit");
        miExit.setToolTipText("Exit application");
        miExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miExitActionPerformed(evt);
            }
        });
        menuFile.add(miExit);

        jMenuBar1.add(menuFile);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        layout.setHorizontalGroup(
        	layout.createParallelGroup(Alignment.TRAILING)
        		.addComponent(jToolBar1, GroupLayout.DEFAULT_SIZE, 411, Short.MAX_VALUE)
        		.addGroup(layout.createSequentialGroup()
        			.addContainerGap()
        			.addComponent(jpOutput, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        			.addContainerGap())
        		.addGroup(Alignment.LEADING, layout.createSequentialGroup()
        			.addContainerGap()
        			.addComponent(jpInput, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        			.addContainerGap())
        );
        layout.setVerticalGroup(
        	layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(layout.createSequentialGroup()
        			.addContainerGap()
        			.addComponent(jpInput, GroupLayout.PREFERRED_SIZE, 110, GroupLayout.PREFERRED_SIZE)
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addComponent(jpOutput, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addComponent(jToolBar1, GroupLayout.PREFERRED_SIZE, 24, GroupLayout.PREFERRED_SIZE))
        );
        getContentPane().setLayout(layout);

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void txtUseCharsKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUseCharsKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        System.out.println("Programatically clicking search-button.");
        btnFindWords.doClick();
    }
}//GEN-LAST:event_txtUseCharsKeyPressed

private void miExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miExitActionPerformed
   System.exit(0);
}//GEN-LAST:event_miExitActionPerformed

private void miClearDictsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miClearDictsActionPerformed
    clearDictionary();
}//GEN-LAST:event_miClearDictsActionPerformed


private void clearDictionary() {
	controller.clearDictionary();
	setStatusListingWordsInDictionary();
}

private void mirbStayOnTopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mirbStayOnTopActionPerformed
    try {
        setAlwaysOnTop(mirbStayOnTop.isSelected());
    } catch (java.lang.SecurityException e1) {
        e1.printStackTrace();
    }
}//GEN-LAST:event_mirbStayOnTopActionPerformed

//    private void miSaveAsDefaultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miSaveAsDefaultActionPerformed
//        java.io.OutputStream outStream = null;
//        try {
//            java.lang.String dictFileNames = "";
//            if (dictionaryFilenames.size() > 0) {
//                for (java.lang.String fileName : dictionaryFilenames) {
//                    dictFileNames += fileName + ", ";
//                }
//                //remove the last ", "
//                dictFileNames = dictFileNames.substring(0, dictFileNames.length() - 2);
//            }
//            properties.setProperty(wordfilesProperty, dictFileNames);
//
//            java.io.File def = new java.io.File(propertyFilename);
//            outStream = new java.io.FileOutputStream(def);
//            properties.store(outStream, java.util.Calendar.getInstance().getTime().toString());
//            lblStatus.setText("Default properties saved.");
//            System.out.println("Written properties to file " + def.getPath());
//        } catch (FileNotFoundException ex) {
//            Logger.getLogger("global").log(Level.SEVERE, "Could not find file to store properties to.", ex);
//            lblStatus.setText("Defaults not saved. Sorry.");
//            ex.printStackTrace();
//        } catch (IOException ex) {
//            Logger.getLogger("global").log(Level.SEVERE, "Could not write file properties to file.", ex);
//            lblStatus.setText("Defaults not saved. Sorry.");
//            ex.printStackTrace();
//        }
//        
//        finally {
//            try {
//                if (outStream != null) {
//                    outStream.close();
//                }
//            } catch (IOException ex) {
//                Logger.getLogger("global").log(Level.SEVERE, null, ex);
//            }
//        }
//}//GEN-LAST:event_miSaveAsDefaultActionPerformed

    
    private void btnFindWordsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFindWordsActionPerformed
        if (controller.getDictionarySize() == 0){
            lblStatus.setText("Please add words to the dictionary first.");
            return;
        }
        
        final String useableChars = txtUseChars.getText().toLowerCase();
        
        if (userHasSetAPattern()) {
        	String pattern = getPattern();
        	lblStatus.setText("Searching for words with pattern ["+ pattern + "] ...");
        	controller.FindWordsWithPattern(useableChars, pattern);
        }
        else {
        	controller.FindWords(useableChars);
        }
    }
    
    private boolean userHasSetAPattern() {
    	String pattern = txtExisting.getText();
        return (pattern != null && pattern.trim().length() != 0);  	
    }
    
    private String getPattern() {
        if (userHasSetAPattern()) {
        	String pattern = txtExisting.getText();
        	if (!pattern.startsWith("^")){
        		pattern = ".*" + pattern;
        	}
        	if (!pattern.endsWith("$")) {
        		pattern += ".*";
        	}
        	return pattern;
    	}
        else {
        	return "";
        }
    }


    public void progress(int percentage){
       jProgressBar1.setValue(percentage); 
    }
    
    public void done(List<String> result) {
        jProgressBar1.setValue(100);
        presentResults(result);
    }
    
    private void presentResults(List<String> results) {
        //sort the list of words according to user choice
        if (jrbAlphabetical.isSelected()) {
            Collections.sort(results);
        } else {
            Collections.sort(results, new Comparator<String>() {

                public int compare(String a, String b) {
                    return b.length() - a.length();
                }
                
            });
        }
        
        //present words
        Document present = new PlainDocument();
        for (String word : results) {
            try {
                present.insertString(present.getLength(), word + "\n", null);
            } catch (BadLocationException ex){
                lblStatus.setText("Error putting words into document.");
                ex.printStackTrace();
            }
        }
        
        jtaWordListing.setDocument(present);
        lblStatus.setText("Found " + results.size() + " words.");
}//GEN-LAST:event_btnFindWordsActionPerformed

    private void initLookAndFeel() {
        try {
            java.lang.String lfName = javax.swing.UIManager.getSystemLookAndFeelClassName();

            javax.swing.UIManager.setLookAndFeel(lfName);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger("global").log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger("global").log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger("global").log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger("global").log(Level.SEVERE, null, ex);
        }
    }

private void miOpenWordfilesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miOpenWordfilesActionPerformed
    int returnVal = dictFileChooser.showOpenDialog(this);
    
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        java.io.File[] files = dictFileChooser.getSelectedFiles();
        List<String> dictionaryFilenames = new LinkedList<String>();
        
        for (int i = 0; i < files.length; i++) {
            File dict = files[i];
            
            controller.addToToDictionary(dict);
            dictionaryFilenames.add(dict.getPath());
        }

        setStatusListingWordsInDictionary();
    }
}//GEN-LAST:event_miOpenWordfilesActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GlottonUI().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    javax.swing.JButton btnClose;
    javax.swing.JButton btnFindWords;
    javax.swing.JDialog dialogAbout;
    javax.swing.JFileChooser dictFileChooser;
    javax.swing.ButtonGroup groupSorting;
    javax.swing.JMenuBar jMenuBar1;
    javax.swing.JMenuBar jMenuBar2;
    javax.swing.JMenuItem jMenuItem4;
    javax.swing.JMenuItem jMenuItem5;
    javax.swing.JProgressBar jProgressBar1;
    javax.swing.JScrollPane jScrollPane1;
    javax.swing.JScrollPane jScrollPane2;
    javax.swing.JSeparator jSeparator1;
    javax.swing.JSeparator jSeparator2;
    javax.swing.JToolBar jToolBar1;
    javax.swing.JPanel jpInput;
    javax.swing.JPanel jpOutput;
    javax.swing.JPanel jpSort;
    javax.swing.JRadioButton jrbAlphabetical;
    javax.swing.JRadioButton jrbLongest;
    javax.swing.JTextArea jtaWordListing;
    javax.swing.JLabel lblStatus;
    javax.swing.JLabel lblUseChars;
    javax.swing.JMenu menuEdit1;
    javax.swing.JMenu menuFile;
    javax.swing.JMenu menuFile1;
    javax.swing.JMenuItem miClearDicts;
    javax.swing.JMenuItem miClearDicts1;
    javax.swing.JMenuItem miExit;
    javax.swing.JMenuItem miExit1;
    javax.swing.JMenuItem miOpenWordfiles;
    javax.swing.JMenuItem miOpenWordfiles1;
    javax.swing.JRadioButtonMenuItem mirbStayOnTop;
    javax.swing.JTextField txtUseChars;
    javax.swing.JTextPane txtpAboutText;
    private JTextField txtExisting;
    private final ButtonGroup buttonGroup = new ButtonGroup();
}
